<template>
  <div>

  </div>
</template>
<script>
import {
  defineComponent,
  onBeforeUnmount,
  onMounted,
  reactive,
  toRefs,
  provide
} from 'vue';
export default defineComponent({
  name: 'Form',
  emits: ["submit"],
  setup(props, { emit }) {
    const state = reactive({
      validateComponents: []
    });
    provide("form", {
      bind,
      unbind
    });
    onMounted(() => {
      state.form.addEventListener("submit", onSubmit);
    });
    onBeforeUnmount(() => {
      state.form.removeEventListener("submit", onSubmit);
    });
    function bind(component) {
      state.validateComponents.push(component);
    }
    function unbind(uid) {
      const index = state.validateComponents.findIndex(c => c.uid === uid);
      if (index > -1) {
        state.validateComponents.splice(index, 1);
      }
    }
    function validate() {
      let valid = true;
      for (const component of state.validateComponents) {
        const result = component.validate();
        if (!result) {
          valid = false
        }
      }
      return valid;
    }
    function onSubmit() {
      const valid = validate();
      if (valid) {
        emit("submit")
      }
    }
  }
})
</script>
<style lang="">

</style>